package team02.server.core.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class TestControllerDispatcher {

	private HttpServletResponse response;
	private RequestWrapper request;
	private String[] queryParams;
	private String target;

	static final String[] QUERY_PARAM_MAPPING = new String[] { "aliasRequest" };

	public TestControllerDispatcher(HttpServletRequest req, HttpServletResponse resp, String queryPath) {

		this.request = new RequestWrapper(req);
		this.response = resp;
		String[] tokens = queryPath.split("/");
		this.queryParams = new String[tokens.length - 1];
		for (int i = 0; i < queryParams.length; i++) {
			queryParams[i] = tokens[i];
		}

		String targetName = tokens[tokens.length - 1];
		this.request.addParameter("targetPage", targetName);
		
		this.target = "/jsp/" + targetName.substring(0, targetName.length() - 3) + "jsp";// test.t02 - t02

//		System.out.println(target);
	}

	public void dispatch() throws IOException, ServletException {
		try {
			dispatch0();
		} catch (ArrayIndexOutOfBoundsException e) {
			this.request.addParameter("error", "Invalid Request");
			this.request.getRequestDispatcher("/default/errorPage.jsp").forward(request, response);
		}
	}

	private void dispatch0() throws ArrayIndexOutOfBoundsException, IOException, ServletException {
		for (int i = 0; i < this.queryParams.length; i++) {
			this.request.addParameter(QUERY_PARAM_MAPPING[i], this.queryParams[i]);
		}
//		PrintWriter out = this.response.getWriter();
//		Enumeration<String> attrName = this.request.getAttributeNames();
//
//		while (attrName.hasMoreElements()) {
//			String name = (String) attrName.nextElement();
//			System.out.print(this.request.getAttribute(name));
//		}

		this.request.getRequestDispatcher(target).forward(request, response);
	}

	public static class RequestWrapper extends HttpServletRequestWrapper {

		public RequestWrapper(HttpServletRequest request) {
			super(request);
		}

		Map<String, String> params = new HashMap<String, String>();

		public void addParameter(String name, String value) {
			if (name == null) throw new NullPointerException("Parameter's name cannot be null");
			params.put(name, value);
		}

		@Override
		public String getParameter(String name) {
			String param = params.get(name);
			if (param != null) return param;
			return super.getParameter(name);
		}
	}
}
